package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

@RequestMapping("/common")
@Slf4j
@RestController
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
public R<String> upload(MultipartFile file) throws IOException {
    String originalFilename = file.getOriginalFilename();
    //获取后缀名
    String lastName = originalFilename.substring(originalFilename.lastIndexOf("."));
    String name = UUID.randomUUID().toString() + lastName;
//创建文件夹作为传入
    File f = new File(basePath);
    if (!f.exists()){
        f.mkdirs();
    }

    file.transferTo(new File(basePath+name));
    return R.success(name);
}

    /**
     * 下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name , HttpServletResponse response)  {
        //从服务端将数据写出给前端浏览器
        try {
            FileInputStream in = new FileInputStream(new File(basePath+name));
            ServletOutputStream out = response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = in.read(bytes))!= -1){
                out.write(bytes,0,len);
            }
            in.close();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }









}
